package com.forte.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import com.forte.shoppingcustomer.ShoppingCustomerService;
import com.forte.shoppingcustomerdao.ShoppingCustomer;

@Component
public class AuthenticationManager implements AuthenticationProvider{

	
	@Autowired
	@Qualifier("shoppingCustomerService")
	private ShoppingCustomerService shoppingCustomerService;
	
	public Authentication authenticate(Authentication authenticate)
			throws AuthenticationException {
		String username = authenticate.getName();
        String password = (String) authenticate.getCredentials();
 
        ShoppingCustomer user = shoppingCustomerService.findCustomerByEmail(username);
 
        if (user == null) {
            throw new BadCredentialsException("Invalid credentials. Please try again.");
        }
 
        if (!password.equals(user.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }
        else
        {
        	 return new UsernamePasswordAuthenticationToken(
        		     authenticate.getName(), 
        		     authenticate.getCredentials()
        		    );
        }
	}

	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return false;
	}

}
